import { isArray } from 'lodash'
import Vue from 'vue'
import {getStore,removeStore} from '@/config/mUtils'
export default (http, store, router) => {
  // 响应拦截
  http.interceptors.response.use(
    response =>{
      if(response.data.status === '10000'){
        // if(response.data.msg){
        //   Vue.$vux.toast.show({text:response.data.msg,type:'warn',time:2000});
        // }
        return Promise.reject(response)
      }else if(response.data.status !== '200'){
        // if(response.data.msg){
        //   Vue.$vux.toast.show({text:response.data.msg,type:'warn',time:2000})
        // }
        return Promise.reject(response)
      }
      return response
    },
    /**
    * 处理响应错误
    */
    (error) => {
      const { response,request } = error
      // 响应超时
      if(request.readyState == 4 && request.status == 0){
        Vue.$vux.toast.show({text:'网络连接超时,请检查网络或者服务器断开连接',type:'warn',time:2000});
        removeStore('wxcode')
        if(getStore('nickname')){
          removeStore('nickname')
        }
        if(getStore('avatar')){
          removeStore('avatar')
        }
        if(getStore('bindMobile')){
          removeStore('bindMobile')
        }
      }
      /**
      * 处理响应没有权限
      */
      if ([401, 400,403].indexOf(response.status) > -1) {
        if(getStore('nickname')){
          removeStore('nickname')
        }
        if(getStore('avatar')){
          removeStore('avatar')
        }
        if(getStore('bindMobile')){
          removeStore('bindMobile')
        }
        removeStore('wxcode')
        router.push({path:'/'})
      }
      if([500,502].indexOf(response.status)>-1){
        removeStore('wxcode')
        if(getStore('nickname')){
          removeStore('nickname')
        }
        if(getStore('avatar')){
          removeStore('avatar')
        }
        if(getStore('bindMobile')){
          removeStore('bindMobile')
        }
        router.push({path:'/'})
      }
      /**
      * 处理错误响应
      */
      if (isArray(response.data)) {
        console.log(response)
        // store.dispatch('setMessage', { type: 'error', message: response.data.messages })
      /**
      * 验证错误消息类新
      */
      } else {
        console.log(response)
        // store.dispatch('setMessage', { type: 'validation', message: response.data })
      }

      // store.dispatch('setFetching', { fetching: false })

      return Promise.reject(error)
    }
  )
}
